<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/views/QuanXian/quanxianguanli/bumenguanli/bumen/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElButton, ElTag,ElSwitch } from 'element-plus'
import { Table } from '@/components/Table'
import { getShuliang,getTableListApi, saveTableApi, delTableListApi,getXiangqin} from '@/api/fankuiapi'
import { useTable } from '@/hooks/web/useTable'
import { TableData } from '@/api/table/types'
import { h, ref, unref, reactive } from 'vue'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { TableColumn } from '@/types/table'
import { FormSchema } from '@/types/form'
import { ElMessage } from 'element-plus'


let daichuli = ref();
let yichuli = ref();
const shu = async () => {
  const res = await getShuliang().catch(() => {})
  if (res){
    daichuli.value = res.data.waitNum
    yichuli.value = res.data.acceptedNum
  }
}
shu();

const { register, tableObject, methods } = useTable<TableData>({
  getListApi: getTableListApi,
  delListApi: delTableListApi,
  response: {
    list: 'list',
    total: 'total'
  },
  defaultParams: {
    title: 's'
  }
})

const { getList, setSearchParams } = methods
tableObject.feedbackStatus =3
getList()

const { t } = useI18n()

//表格的虚拟数据
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'feedbackId',
    label: '序号',
    type: 'index',
  },
  {
    field: 'account',
    label:'用户账号'
  },
  {
    field: 'feedbackType',
    label:'意见反馈类型',
    formatter: (row, column, cellValue, index) => {
      if (cellValue == 2){
        return '视频反馈'
      }else if(cellValue == 3){
        return '商品反馈'
      }else if(cellValue == 4){
        return '其他反馈'
      }
    }
  },
  {
    field: 'feedbackClassification',
    label:'意见分类',
    formatter: (row, column, cellValue, index) => {
      if (cellValue == 2){
        return '很好'
      }else if(cellValue == 3){
        return '好'
      }else if(cellValue == 4){
        return '一般'
      }else if(cellValue == 5){
        return '差'
      }
    }
  },
  {
    field: 'createDate',
    label:'反馈时间',
    formatter: (row, column, cellValue, index) => {
      let format = 'YYYY-mm-dd HH:MM:SS'
      let date = new Date(cellValue);
      const dataItem = {
        'Y+': date.getFullYear().toString(),
        'm+': (date.getMonth() + 1).toString(),
        'd+': date.getDate().toString(),
        'H+': date.getHours().toString(),
        'M+': date.getMinutes().toString(),
        'S+': date.getSeconds().toString(),
      };
      Object.keys(dataItem).forEach((item) => {
        const ret = new RegExp(`(${item})`).exec(format);
        if (ret) {
          format = format.replace(ret[1], ret[1].length === 1 ? dataItem[item] : dataItem[item].padStart(ret[1].length, '0'));
        }
      });
      return format
    }
  },
  {
    field: 'feedbackContent',
    label:'反馈内容'
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const crudSchemastwo = reactive<CrudSchema[]>([
  {
    field: 'trueName',
    label:'受理人'
  },
  {
    field: 'createDate',
    label:'受理时间',
    formatter: (row, column, cellValue, index) => {
      let format = 'YYYY-mm-dd HH:MM:SS'
      let date = new Date(cellValue);
      const dataItem = {
        'Y+': date.getFullYear().toString(),
        'm+': (date.getMonth() + 1).toString(),
        'd+': date.getDate().toString(),
        'H+': date.getHours().toString(),
        'M+': date.getMinutes().toString(),
        'S+': date.getSeconds().toString(),
      };
      Object.keys(dataItem).forEach((item) => {
        const ret = new RegExp(`(${item})`).exec(format);
        if (ret) {
          format = format.replace(ret[1], ret[1].length === 1 ? dataItem[item] : dataItem[item].padStart(ret[1].length, '0'));
        }
      });
      return format
    }
  },
  {
    field: 'remark',
    label:'受理结果',

  },
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const dialogVisible = ref(false)

const dialogTitle = ref('')

const delLoading = ref(false)

const delData = async (row: TableData | null, multiple: boolean) => {
  tableObject.currentRow = row
  const { delList, getSelections } = methods
  const selections = await getSelections()
  delLoading.value = true
  await delList(
    multiple ? selections.map((v) => v.feedbackId) : tableObject.currentRow?.feedbackId,
    multiple
  ).finally(() => {
    delLoading.value = false
  })
}

const actionType = ref('')

const action = async(row: TableData, type: string) => {
  dialogTitle.value = t(type === 'edit' ? '受理用户反馈信息' : 'exampleDemo.detail')
  if (row != null){
      actionType.value = type
      tableObject.currentRow = row
      dialogVisible.value = true
    }
  }

const actiontwo = async(row: TableData, type: string) => {
  dialogTitle.value = t(type === 'edit' ? '受理用户反馈信息' : 'exampleDemo.detail')
  if (row != null){
    const res = await getXiangqin({"remark":row.feedbackId}).catch(() => {})
    if (res) {
      res.data.remark = "已受理"
      actionType.value = type
      tableObject.currentRow = res.data
      dialogVisible.value = true
    }
  }
}

const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  await write?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = (await write?.getFormData()) as TableData
      if (data!=null){
        data.feedbackStatus = 4
      const res = await saveTableApi(data)
        .catch(() => {})
        .finally(() => {
          loading.value = false
        })
      if (res) {
        dialogVisible.value = false
        tableObject.currentPage = 1
        ElMessage({
          message: '受理成功！',
          type: 'success',
        })
        shu()
        getList()
      }
      }
    }
  })
}

allSchemas.searchSchema = reactive<FormSchema[]>([
  {
    field: 'account',
    label: '用户账号',
    component: 'Input',
  },
  {
    field: 'feedbackType',
    label: '反馈类型',
    component: 'Select',
    componentProps: {
      options: [
        {
          label:'请选择类型',
          value:''
        },
        {
          label:'视频反馈',
          value:2
        },
        {
          label:'商品反馈',
          value:3
        },
        {
          label:'其他反馈',
          value:4
        }
      ]
    }
  },
  {
    field: 'feedbackClassification',
    label: '意见反馈',
    component: 'Select',
    componentProps: {
      options: [
        {
          label:'请选择分类',
          value:''
        },
        {
          label:'很好',
          value:2
        },
        {
          label:'好',
          value:3
        },
        {
          label:'一般',
          value:4
        },
        {
          label:'差',
          value:5
        }
      ]
    }
  }
])
let isActive = ref(true)
let hasError = ref(false)
let isActive2 = ref(false)
let hasError2 = ref(true)
  //变换按钮
  const bianhuan = async() => {
   isActive.value = true;
   hasError.value = false;
    isActive2.value = false;
    hasError2.value = true;
    tableObject.feedbackStatus =3
    getList()
  }

const bianhuan2 = async() => {
  isActive2.value = true;
  hasError2.value = false;
  isActive.value = false;
  hasError.value = true;
  tableObject.feedbackStatus =4
  getList()
}
</script>

<template>
  <div class="pre_home">
    <div class="div_tit">
      <div class="div_ic"></div>
      <p class="tit_span">用户反馈列表</p>
    </div>
    <div class="div_btn">
      <ul>
        <li class="btn_li_item">
          <button :class="{ div_btn_class: isActive, 'div_btn_classtwo': hasError }" @click="bianhuan">
            待审核  (<span class="span_Num" id="waitNum">{{daichuli}}</span>)
          </button>
        </li>
        <li class="btn_li_item">
          <button :class="{ div_btn_class: isActive2, 'div_btn_classtwo': hasError2 }" @click="bianhuan2">
            已受理  (<span class="span_Num" id="acceptedNum">{{yichuli}}</span>)
          </button>
        </li>
      </ul>
    </div>
    <div class="div_index">
      <div class="div_index_title">
        <Icon icon="tabler:search" />
        筛选查询
      </div>
    </div>
  <ContentWrap>
    <div style="width: 2000px">
      <Search
              :model="{ title: '' }"
              :schema="allSchemas.searchSchema"
              @search="setSearchParams"
              @reset="setSearchParams"
      />
    </div>
  </ContentWrap>
  <ContentWrap>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList.slice((tableObject.currentPage - 1) * tableObject.pageSize,tableObject.currentPage * tableObject.pageSize)"
      :loading="tableObject.loading"
      :pagination="{
        total: tableObject.total
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton type="primary" v-hasPermi="['example:dialog:edit']" @click="action(row, 'edit')" v-if="tableObject.feedbackStatus ==3">
          受理
        </ElButton>
        <ElButton type="primary" v-hasPermi="['example:dialog:detail']" @click="actiontwo(row, 'detail')" v-if="tableObject.feedbackStatus ==4">
          受理详情
        </ElButton>
        <ElButton type="success" v-hasPermi="['example:dialog:edit']" @click="action(row, 'edit')" v-if="tableObject.feedbackStatus ==4">
          查看
        </ElButton>
        <ElButton type="danger" v-hasPermi="['example:dialog:delete']" @click="delData(row, false)" v-if="tableObject.feedbackStatus ==4">
          {{ t('exampleDemo.del') }}
        </ElButton>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Write
      v-if="actionType !== 'detail'"
      ref="writeRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />

    <Detail
      v-if="actionType === 'detail'"
      :detail-schema="crudSchemastwo"
      :current-row="tableObject.currentRow"
    />

    <template #footer>
      <ElButton v-if="actionType === 'edit' && tableObject.feedbackStatus !=4" type="primary" :loading="loading" @click="save">
        受理
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
  </div>
</template>

<style lang="less" scoped>
  .pre_home{
    width:100%;
    height:100%;
  }
  .div_tit{
    margin-left: 0.1%;
    width:99%;
    height:50px;
    background-color:#F2F2F2;
    border:2px solid #E6E6E6;
    position: relative;
  }
  .tit_span{
    margin-left:10px;
    margin-top:-20px;
    color:#999999;
  }

  .div_ic{
    width:5px;
    height:20px;
    background-color:#1ABC9C;
    margin-top:15px;
  }
  .div_btn{
    margin-left: 2.5%;
    margin-right:20px;
    width:96%;
    height:50px;
    margin-bottom:10px;
  }
  .btn_li_item{
    margin-top:13px;
    width:140px;
    float:left;
  }
  .div_btn_class{
    width:130px;
    height:35px;
    background-color: #31A99F;
    color: white;
    border: 1px solid black;
  }
  .div_btn_classtwo{
    width:130px;
    height:35px;
    background-color: white;
    color: black;
    border: 1px solid black;
  }
  .span_Num{
    color: #ff4624;
    font-weight: bold;
  }
  .div_index_ul1{
    overflow: hidden;
    width: 210px;
    position: absolute;
    right: -17px;
  }
  .div_index_title{
    width:100%;
    height:55px;
    background-color:#F3F3F3;
    border-bottom:1px solid #E6E6E6;
    font-weight:bold;
    line-height:55px;
    font-size:16px;
    text-indent:18px;
    color:#666666;
  }
</style>
